<?php

class OrderManager {
	
	public static function getAccountPromoCode() {
		$authorized = CirrusInsight::Authorized();

		if ($authorized) {
			$user = new InsightUser();
			$ctrlPanel_svc = OrderManager::getCustomWsSession('ControlPanel');
			$orgInfo = $ctrlPanel_svc->getOrgLicenseInfo(array("organizationId"=>$user->org_id));
			
			if (isset($orgInfo->result->promoCode)) {
				return $orgInfo->result->promoCode;
			}
		}
		
		return null;
	}
	
	public static function createOrder($user_id, $stripe_token, $order_detail) {
		$order_svc = OrderManager::getCustomWsSession('CIOrder');
		
		$args = array(
			"sfuserId" => $user_id,
			"stripe_token" => $stripe_token,
			"details" => $order_detail
		);
		$res = $order_svc->createOrder($args);

		try {
			// Set Affiliate Referrer
			if ($res->result->isSuccess && isset($_REQUEST["referrer"])) {
				// get the account related to the order and set the referrer
				$soql = "Select Cirrus_Insight_License__c, Cirrus_Insight_License__r.Affiliate__c from Opportunity Where Id ='{$res->result->oppId}'";
				$res2 = OrderManager::$cp_conn->query($soql);
				$opp = $res2->records[0];
				
				if ($opp->fields->Cirrus_Insight_License__r != null && $opp->fields->Cirrus_Insight_License__r->fields->Affiliate__c == null) {
					$soql = "Select Id From Account Where Affiliate_Code__c = '{$_REQUEST["referrer"]}'";
					$res3 = OrderManager::$cp_conn->query($soql);
					if (count($res3->records)) {
						$partner = $res3->records[0];
				
						$lic = new SObject();
						$lic->type = "Cirrus_Insight_License__c";
						$lic->fields = array(
							"Id" => $opp->fields->Cirrus_Insight_License__c,
							"Affiliate__c" => $partner->Id
						);
						
						$res4 = OrderManager::$cp_conn->update(array($lic));
					}
					
					// erase the cookie
				  setcookie(
				    $name="insight_referrer",
				    $value=null,
				    $expires=time()-90000,
				    $path="/",
				    $domain=".cirrusinsight.com",
				    $secure=true,
				    $secureOnly=true
				  );

					// Set Lead Source Detail
					if ($res->result->isSuccess && isset($_REQUEST["which"])) {
						$opp = new SObject();
						$opp->type = "Opportunity";
						$opp->fields = array(
							"Id" => $res->result->oppId,
							"Lead_Source_Detail__c" => $_REQUEST["which"]
						);
						$res5 = OrderManager::$cp_conn->update(array($opp));
					}
				}
			}
		} catch (Exception $e) {
			Util::mailCI("Error setting referrer", array("exception"=>$e), false);
		}
		
		return $res;
	}
	
	public static function getPricing($qty, $freq, $promo) {
		$pricing_svc = OrderManager::getCustomWsSession('ccg_enhprd/ItemMaster');
		
		// Create Payment Record
		$args = array(
			"itemCode" => ITEM_CODE,
			"pricebookId" => PRICE_BOOK,
			"quantity" => $qty,
			"frequency" => $freq, // monthly or annually
			"promo_code" => $promo
		);
		
		try {
			$res = $pricing_svc->getItemPromotionPrice($args);
			$res->result->isSuccess = true;
			return $res->result;
		} catch (SoapFault $e) {
			$res = new stdClass();
			$res->isSuccess = false;
			$res->message = "Could not retrieve pricing";
			return $res;
		}
	}
	
	public static $cp_conn;
	private static function getCustomWsSession($ws_name) {
		Salesforce::$cirruspath = true;
		OrderManager::$cp_conn = Salesforce::connect();
		
		$parsedURL = parse_url(OrderManager::$cp_conn->getLocation());
		$sfdc_server = substr($parsedURL['host'],0,strpos($parsedURL['host'], '.'));
		$ws_wsdl = str_replace('/', '_', $ws_name) . '.xml';
		$ws_endpoint = 'https://' . $sfdc_server . '.salesforce.com/services/wsdl/class/' . $ws_name;
		$ws_namespace = 'http://soap.sforce.com/schemas/class/' . $ws_name;
		
		if (!file_exists($ws_wsdl)) {
			Util::cacheWSDL($ws_endpoint, $ws_wsdl, OrderManager::$cp_conn->getSessionId());
		}
		
		// SOAP Client for Web Service
		$custom_svc = new SoapClient($ws_wsdl);
		$sforce_header = new SoapHeader($ws_namespace, "SessionHeader", array("sessionId" => OrderManager::$cp_conn->getSessionId()));
		$custom_svc->__setSoapHeaders(array($sforce_header));
		
		return $custom_svc;
	}
	
}

?>